<?php

namespace addons\tpmecms\controller;

use think\addons\Controller;
use think\Db;
use think\Config;
use fast\Tree;
use think\Request;

class Cms extends Controller
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $config;
    protected $theme;

    static public $nav;
    

    public function _initialize()
    {   
     

        parent::_initialize();
        $this->config = get_addon_config('tpmecms');
        self::$nav = $this->get_nav_list();

        $this->view->assign('nav', self::$nav);//导航栏
        if($this->auth->id){    //页面加入用户信息
            $this->view->assign('user', $this->auth->getUserinfo());//用户
        }
        
    }

    // 初始化
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        
        //主题配置
        switch ($this->config['theme']) {
            case 'auto':                
                if($this->request->isMobile()){
                    //跳转到手机端
                    $this->theme = 'mobile';
                }else{
                    $this->theme = 'pc';
                }

                break;
            case 'pc':
                $this->theme = 'pc';
                break;
            case 'mobile':
                $this->theme = 'mobile';
                break;
            default:
                $this->theme = 'pc';
                break;
        }
        
        $this->view->assign('tpmecms', $this->config);

        // 设定主题模板目录
        $this->view->engine->config('view_path', $this->view->engine->config('view_path') . $this->theme . DS);
        // 加载自定义标签库
        $this->view->engine->config('taglib_pre_load', 'addons\tpmecms\taglib\Tp');
        // 默认渲染栏目为空
        // $this->view->assign('__CHANNEL__', null);
        // 定义CMS首页的URL
        // \think\Config::set('cms.indexurl', addon_url('tpmecms/index/index', [], false));
    }



    /**
     * 首页
     *
     * @return void
     */
    public function index()
    {
        
        return $this->view->fetch();
    }


    /**
     * 获取导航栏列表
     *
     * @param integer $limit 默认15个
     * @param integer $pid 上级的id（默认为0全部
     * @return void
     */
    protected function get_nav_list($pid = 0,$limit=15)
    {
        $nav_list = Db::name('tpmecms_cate')
            ->where('isnav_switch',1)
            ->where('status','1')
            ->order('weigh desc')
            ->select();

        $nav_list_ids = Db::name('tpmecms_cate')
            ->where('isnav_switch',1)
            ->where('status','1')
            ->order('weigh desc')
            ->column('parent_id,name','id');

        foreach($nav_list as &$val){

            if(empty($val['outlink'])){
                //加入路由开关
                if(get_addon_config('tpmecms.route_switch')){
                    $val['url'] = '/'.$val['diyname'];
                }else{
                    // $val['url'] = '/addons/tpmecms/index/cate/id/'.$val['id'];
                    $val['url'] = addon_url('tpmecms/index/cate', [':name'=>$val['diyname'], 'id'=>$val['id']]);
                }
                
            }else{
                $val['url'] = $val['outlink'];
            }
        }


        $Tree = Tree::instance();
        $Tree->init($nav_list, 'parent_id');
        $list = $Tree->getTreeArray($pid, 'parent');

        
        
        return $list;
    }


    /**
     * 获取栏目信息
     *
     * @param int $id 栏目id
     * @return void
     */
    public function get_cate_data($id)
    {
        $cate = Db::name('tpmecms_cate')->find($id);
        if(!$cate){
            $this->error('没有该栏目');
        } 

        $nav_list_ids = Db::name('tpmecms_cate')
            ->where('isnav_switch',1)
            ->where('status','1')
            ->order('weigh desc')
            ->column('parent_id,name','id');
        $cate['is_top'] = $this->getCateTop($cate);//顶级栏目id

        return $cate;
    }


    /**
     * 获取栏目顶级id
     * 
     * @param array $cate 栏目信息
     * @return void
     */
    public function getCateTop($cate)
    {
        if($cate['parent_id']>0){
            $p_cate = Db::name('tpmecms_cate')->find($cate['parent_id']);
            return $this->getCateTop($p_cate);
        }else{
            return $cate['id'];
        }
    }

    /**
     * 获取栏目文章列表
     *
     * @param int $id 栏目id
     * @param int $page 页
     * @param int $limit 每页数量
     * @param string $field 排序字段
     * @param string $sort 排序{升(asc)降(desc)}
     * @return void
     */
    public function get_cate_art_list($id=null,$page=1,$limit=null,$field='weigh',$sort='desc')
    {
        $where = null;
        if($id){
            $where['id'] = ['=',$id];

            if(!$limit){
                $pagesize = $this->get_cate_data($id)['pagesize'];
                $limit = $pagesize?$pagesize:10;
            }
        }else{
            if(!$limit)
                $limit = 10;
        }
        
        $list = Db::name('article')
            ->where($where)
            ->page($page,$limit)//翻页及数量
            ->order($field.' '.$sort)//排序
            ->select();
       
        return $list;
    }




    /**
     * 获取单页内容
     *
     * @param array $cate 栏目信息
     * @return void
     */
    public function get_page_data($cate)
    {
        return  Db::name('tpmecms_page')
            ->where('cate_id',$cate['id'])
            ->find();        
    }

    /**
     * 获取栏目文章列表
     *
     * @param int $id 栏目id
     * @param int $page 页
     * @param int $limit 每页数量
     * @param string $field 排序字段
     * @param string $sort 排序{升(asc)降(desc)}
     * @return void
     */
    public function get_cate_art_list2($cate,$page=1,$field='weigh',$sort='desc')
    {
        $where['status'] = '1';//需要状态为1才显示

        //可以直接get或post提交各种参数自行添加条件
        $params = $this->request->param();
        if(isset($params['tag'])){
            $where['tags'] = ['like',"%".$params['tag']."%"];
        }
        //例如前段直接传page参数
        if(isset($params['page'])){
            $page = $params['page'];
        }

        //同一个表可以多个分类
        if($cate['parent_id']>0){
            //如果这个表里面有这个字段(兼容其他表判断)
            $is_cate_id = Db::query("Describe ".$cate['table_name']." cate_id");
            if($is_cate_id){
                $where['cate_id'] = $cate['id'];
            }

            //如果这个表里面有这个字段(兼容其他表判断)
            $is_deletetime = Db::query("Describe ".$cate['table_name']." deletetime");
            if($is_deletetime){
                $where['deletetime'] = NULL;//如果删除，但没有被真是删除（在回收站），就不显示
            }
            
        }
      
        $limit = $cate['pagesize'];//分页数量
        $list = Db::table($cate['table_name'])
                ->where($where)
                ->order($field.' '.$sort)//排序
                ->page($page,$limit)
                ->limit($limit)
                ->select();
            

        //*******************翻页自定义区域
        //翻页总数
        $page_data['count']= Db::table($cate['table_name'])
                ->where($where)
                ->count();
        //总页数                有余进1
        $page_data['pages'] = intval(ceil($page_data['count']/$limit));//修复浮点问题2021-07-02 10:44:43
       
        //一页数量
        $page_data['limit'] = $limit;

        //当前页码
        $page_data['page'] = $page;

        //页码列表  可以循环list
        $page_data['list'] = null;
        for ($i=1; $i <=$page_data['pages'] ; $i++) {      
            $page_data['list'][] = ['url'=>$this->get_page_url($cate['id'],$i) , 'num'=>$i];
        }

        //第一页
        $page_data['first_page'] = ['num'=>1,'url'=>$this->get_page_url($cate['id'] , 1)]; //2021-07-02 10:44:43
        
        //上一页
        $page_data['prev_page'] = $page>1 ? ['num'=>$page-1,'url'=>$this->get_page_url($cate['id'] , $page-1)]: null;        
        
        //下一页
        $page_data['next_page'] = $page_data['pages']>$page ? ['num'=>$page+1,'url'=>$this->get_page_url($cate['id'] , $page+1)] : null;

        //最后一页
        $page_data['last_page'] = $page_data['pages']?['num'=>$page_data['pages'],'url'=>$this->get_page_url($cate['id'] , $page_data['pages'])] : null;//2021-07-02 10:44:43
        
        //可以自行打断查看数据 ⌚️2021-06-23 22:09:59
        // halt($page_data);

        $this->view->assign('page' , $page_data);
        //*******************翻页自定义区域结束




        foreach ($list as $key => &$val) {
            //没有外链 就生成（也可以自己注释了在前段判断）
            if(!isset($val['outlink']) || empty($val['outlink'])){
                $val['url'] = $this->get_show_url($cate['id'],$val['id']);
            }else{
                $val['url'] = $val['outlink'];
            }
           
        }
        

        return $list;
    }


    /**
     * 获取分页数
     *
     * @param string $table_name 表名
     * @return void
     */
    public function get_limit($table_name)
    {
        $cate = Db::name('tpmecms_cate')->where('table_name',$table_name)->find();
        if(!$cate){
            $this->error('没有该数据表');
        }
        return $cate['pagesize'];
    }



    /**
     * 获取栏目信息
     *
     * @param string $table_name 表名
     * @return void
     */
    public function get_cate_data_By_table_name($table_name)
    {
        $cate = Db::name('tpmecms_cate')->where('table_name',$table_name)->find();
        if(!$cate){
            $this->error('没有该数据表');
        }
        return $cate;
    }

    /**
     * 获取显示页面
     *
     * @param string $cate_id 栏目id
     * @param int $id 内容id
     * @return void
     */
    public function get_show_url($cate_id,$id)
    {
        //也可以自己定义自己的url
        $cate = Db::name('tpmecms_cate')->find($cate_id);
        if($this->config['route_switch']){
            
            return '/'.$cate['diyname'].'_show/'.$id;
        }else{
            // return '/addons/tpmecms/index/show/cate_id/'.$cate_id.'/id/'.$id;
            return addon_url('tpmecms/index/show', [':name'=>$cate['diyname'], 'cate_id'=>$cate_id,'id'=>$id]);
        }
    }


    /**
     * 获取字段数组（可处理时间戳）
     *
     * @param array $arr 数组
     * @param array $fields 需要的字段
     * @param array $NotNull 不能为空默认为假
     * @return void
     */
    protected function get_field_arr($arr,$fields,$NotNull=false)
    {
        if(!is_array($fields)){
             //字符串
             $fields = explode(',',$fields);
        }
        
        $new = array();
        foreach($fields as $key=>$val){
        
                if(isset($arr[$val])){
                    if(!$arr[$val])$this->error('请内容信息');
                    $new[$val] = $arr[$val];

                }elseif($NotNull){
                    $this->error('请提交完整的信息');
                }
            
        }
        return $new;
    }

    /**
     * 获取翻页连接
     *
     * @param int $cate_id 栏目id
     * @param int $page 页码
     * @return void
     */
    public function get_page_url($cate_id,$page)
    {
        // $cate_id = $this->request->param('cate_id');
        // $page = $this->request->param('page',1);
        $cate = Db::name('tpmecms_cate')->find($cate_id);
        if($this->config['route_switch']){
          
            // return $this->request->domain().'/addons/tpmecms/index/cate/id/'.$cate_id.'/page/'.$page;
            // return $this->request->domain().'/'.$cate['diyname'].'/page/'.$page;
            return addon_url($cate['diyname'], [ 'page'=>$page]);
        }else{
            // return $this->request->domain().'/addons/tpmecms/index/cate/id/'.$cate_id.'/page/'.$page;
            return addon_url('tpmecms/index/cate', [ 'page'=>$page,'id'=>$cate_id]);
        }
        
    }



    static function getCateUrl($v){
        //判断是否直接跳转
        if(trim($v['outlink'])!==''){
            $v['url'] = trim($v['outlink']);
        }else{
            // $v['url'] = '/tpmecms/index/cate?id='.$v['id'];
            $v['url'] = addon_url('tpmecms/index/cate', ['id' => $v['id']]);
            //判断是否跳转到下级栏目
            // if($v['is_next']==1){
            //     $is_next = Db::name('cate')->where('parentid',$v['id'])->order('sort ASC,id DESC')->find();
            //     if($is_next){
            //         $v['url'] = getCateUrl($is_next);
            //     }
            // }else{
            //     $moduleurl = Db::name('module')->where('id',$v['moduleid'])->value('name');
            //     if($v['catdir']){
            //         $v['url'] = url(request()->module().'/'.$v['catdir'].'/index', 'catId='.$v['id']);
            //     }else{
            //         $v['url'] = url(request()->module().'/'.$moduleurl.'/index', 'catId='.$v['id']);
            //     }
            // }
        
        }
        return $v['url'];
    }


    static function changeFields($list,$cate_id){
        $info = [];
        foreach ($list as $k=>$v){
            $url = self::getShowUrl($v,$cate_id);
        
            // $list[$k] = changeField($v);
            $info[$k] = $list[$k];//定义中间变量防止报错
            $info[$k]['url'] = $url;
        }
        return $info;
    }




    //获取详情URL
    static function getShowUrl($v,$cate_id){
        if($v){
            // $url = '/tpmecms/index/show/cate_id/'.$cate_id.'/id/'.$v['id'];
            $url = addon_url('tpmecms/index/show', ['cate_id'=>$cate_id,'id'=>$v['id']]);
        }
        return $url;
    }
}
